package com.cff.action.user;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cff.domain.User;
import com.cff.domain.UserType;
import com.cff.service.cache.SpecialUserCache;
import com.cff.service.user.UserService;
import com.cff.util.StringUtil;

import net.sf.json.JSONObject;

@Controller("userController")
@RequestMapping("/user")
public class UserAction {
protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	UserService userService;
	@Autowired
	SpecialUserCache specialUserCache;
	
	@RequestMapping(value="/check/loginId")
	public void checkLoginId(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String loginId = request.getParameter("loginId");
		
		Boolean result = userService.checkLoginIdUsed(loginId);
    
		logger.info("结果{}"+result);
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("status","200");
		if(result){
			map.put("status","100");
		}
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	
	@RequestMapping(value="/register")
	public void register(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		User user = new User();
		user.setLoginId(loginId);
		user.setPasswd(password);
		Boolean result = false;
		try{
			result = userService.register(user);
		}catch(Exception e){
			result = false;
		}
    
		logger.info("结果{}"+result);
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("status","200");
		if(!result){
			map.put("status","100");
		}else{
			HttpSession session = request.getSession(false);
		    session.setAttribute("userInfo", user);
		}
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/login")
	public void login(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		User user = new User();
		user.setLoginId(loginId);
		user.setPasswd(password);
		Boolean result = userService.login(user);
    
		logger.info("结果{}"+result);
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("status","200");
		if(!result){
			map.put("status","100");
		}else{
			HttpSession session = request.getSession(false);
		    session.setAttribute("userInfo", user);
		}
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/loginout")
	public String loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception{
		HttpSession session = request.getSession(false);
	    session.removeAttribute("userInfo");
		
		return "/index.jsp";
	}
	
	@RequestMapping(value="/modifypasswd")
	public String modifyPasswd(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		String passwordnew = request.getParameter("passwordnew");
		String passwordconfirm = request.getParameter("passwordconfirm");
		logger.info(passwordnew+"----" + passwordconfirm);
		if(!passwordnew.equals(passwordconfirm)){
			logger.info("两次密码不一致");
			return "/jsp/user/userManager.jsp?type=101";
		}
		if(StringUtil.isEmpty(loginId)){
			logger.info("无登陆id");
			return "/index.jsp";
		}
		
		User user = new User();
		user.setLoginId(loginId);
		user.setPasswd(password);
		if(userService.login(user)){
			user.setPasswd(passwordnew);
			logger.info("密码正确");
			if(userService.modify(user)){
				return "/jsp/user/userManager.jsp?type=200";
			}
			return "/jsp/user/userManager.jsp?type=102";
		}
		
		return "/jsp/user/userManager.jsp?type=100";
	}
	
	@RequestMapping(value="/shirologin")
	public void shiroLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		User user = new User();
		user.setLoginId(loginId);
		user.setPasswd(password);
		UsernamePasswordToken token = new UsernamePasswordToken(loginId, password);
		Subject currentUser = SecurityUtils.getSubject(); 
		HashMap<String,Object> map = new HashMap<String, Object>();
        try {  
            currentUser.login(token);//验证角色和权限  
    		token.setRememberMe(true); 
            HttpSession session = request.getSession(false);
            if(loginId.matches("168[0-9]{8}")){
            	user.setUserType("1001");//客服
            }else{
            	user.setUserType("0001");//普通
            }
		    session.setAttribute("userInfo", user);
		    map.put("status","200");
        } catch (Exception e) {  
            logger.error(e.getMessage());  
            map.put("status","100");
        }  
        JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	@RequestMapping(value="/usertype")
	public void usertype(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String userType = request.getParameter("userType");
		logger.info("userType:" + userType);
		List<UserType> users = specialUserCache.findSpecialUser(userType);
		HashMap<String,Object> map = new HashMap<String, Object>();
		
		map.put("users",users);
		JSONObject json = JSONObject.fromObject(map);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());
	}
	
	public static void main(String args[]){
		String loginId="1688888111";
		if(loginId.matches("168[0-9]{8}")){
			System.out.println("match");
		}else{
			System.out.println("not match");
		}
	}
}
